﻿using System;
using System.Collections.Generic;
using System.Linq;
using ExtendedMvc.Common.Diagnostics;
using ExtendedMvc.Common.EntityFramework;

namespace ExtendedMvc.WebTest.Model {
	public class LogicalRepository<TEntity> : BaseRepository<TEntity>, ILogicalRepository<TEntity>
		where TEntity : class, ILogicalEntity, IBaseEntity {

		public LogicalRepository() : base() { }

		public virtual IEnumerable<TEntity> All(bool includeDeleted = false) {
			return base.All().Where(entity => includeDeleted || !entity.Deleted);
		}

		public virtual bool Exists(long id, bool includeDeleted = false) {
			Check.Argument.IsNotNegative(id, "id");

			return All(includeDeleted).Any(entity => entity.Id == id);
		}

		public virtual TEntity GetById(long id, bool includeDeleted = false) {
			Check.Argument.IsNotNegative(id, "id");

			return All(includeDeleted).SingleOrDefault(entity => entity.Id == id);
		}

		public virtual IEnumerable<TEntity> Filter(Func<TEntity, bool> predicate, bool includeDeleted = false) {
			Check.Argument.IsNotNull(predicate, "predicate");

			return All(includeDeleted).Where(predicate);
		}

		public virtual long Count(Func<TEntity, bool> predicate = null, bool includeDeleted = false) {
			if (predicate == null) return All(includeDeleted).Count();
			return All(includeDeleted).Count(predicate);
		}

		public override void Delete(TEntity entity) {
			Check.Argument.IsNotNull(entity, "entity");

			entity.Deleted = true;
		}
	}
}
